import axios from 'axios';
import { message, notification, Modal } from 'ant-design-vue';
import qs from 'qs';
import store from '@/store';
import { getToken } from '@/utils/session'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 10000,
  responseType: 'json'
});

// 免token验证URL
const exits = [
  '/captcha/get',
  '/captcha/check',
  '/login'
]

const toLogin = () => {
  store.dispatch('user/logout')
  location.href = '/index'
}

//请求
service.interceptors.request.use(request => {
  // 是否需要设置 token
  const isToken = (request.headers || {}).isToken === false
  if (getToken() && !isToken && exits.indexOf(request.url) === -1) {
    request.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (request.method === 'get' && request.params) {
    let url = request.url + '?'
    for (const propName of Object.keys(request.params)) {
      const value = request.params[propName]
      var part = encodeURIComponent(propName) + '='
      if (value !== null && typeof value !== 'undefined') {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            let params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + '='
            url += subPart + encodeURIComponent(value[key]) + '&'
          }
        } else {
          url += part + encodeURIComponent(value) + '&'
        }
      }
    }
    url = url.slice(0, -1)
    request.params = {}
    request.url = url
  }
  return request
}, error => {
  console.log(error)
  Promise.reject(error)
});

//响应
service.interceptors.response.use(
  response => {
    const code = response.data.code || response.data.repCode || ''
    const msg = response.data.msg || response.data.repMsg || ''
    if (code === 200 || code === '0000') {
      return Promise.resolve(response)
    } else if (code === 401) {
      Modal.confirm({
        title: '温馨提示',
        content: `登录状态已过期，您可以继续留在该页面，或者重新登录`,
        okText: '重新登录',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          toLogin()
        }
      })
    }  else if (code === 500) {
      message.error(msg)
      return Promise.reject(new Error(msg))
    }  else if (code !== 200) {
      notification.error({
        message: '温馨提示',
        description: msg
      });
      return Promise.reject('error')
    } else {
      message.error(msg)
      return Promise.reject(response)
    }
  },
  error => {
    return Promise.reject(error)
  }
)

let http = {};

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

http.get = function(url, params = null) {
  return new Promise((resolve, reject) => {
    service.get(url, { params }).then(res => {
      resolve(res.data);
    }).catch(e => {
      reject(e);
    });
  });
};

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

http.post = function(url, params) {
  return new Promise((resolve, reject) => {
    service.post(url, qs.stringify(params)).then(res => {
      resolve(res.data);
    }).catch(e => {
      reject(e);
    });
  });
};

http.postJson = function(url, params) {
  return new Promise((resolve, reject) => {
    service.post(url, params).then(res => {
      resolve(res.data)
    }).catch(e => {
      reject(e)
    })
  })
}

export default http;
